using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WhereWolf
{
	public partial class frmFolderPicker : Form
	{
		public frmFolderPicker()
		{
			InitializeComponent();
		}

		private ArrayList m_subDirs;

		public ArrayList SelectedDirectories
		{
			get { return m_subDirs; }
			set { m_subDirs = value; }
		}
	

		private void frmFolderPicker_Load(object sender, EventArgs e)
		{
			SelectedDirectories = new ArrayList();

			try
			{
				foreach (DriveInfo logicalDrive in DriveInfo.GetDrives())
				{
					TreeNode oNode = new TreeNode();
					oNode.ImageIndex = 0;
					oNode.SelectedImageIndex = 0;
					oNode.Text = logicalDrive.Name;
					tvFolders.Nodes.Add(oNode);
					oNode.Nodes.Add("");
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("Cannot create initial node: " + ex.ToString());
				throw;
			}
		}

		private void GetAllChecked(TreeNodeCollection oNodes)
		{
			foreach (TreeNode tNode in oNodes)
			{
				if (tNode.Checked)
				{
					SelectedDirectories.Add(tNode.FullPath.Replace("\\\\", "\\"));
				}

				GetAllChecked(tNode.Nodes);
			}
		}


		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}


		private void btnOK_Click(object sender, EventArgs e)
		{
			GetAllChecked(tvFolders.Nodes);
			this.Close();
		}
	

		private void tvFolders_BeforeExpand(object sender, TreeViewCancelEventArgs e)
		{
			if (e.Node.ImageIndex != 2)
			{
				try
				{
					if ((e.Node.GetNodeCount(false) == 1) && (e.Node.Nodes[0].Text == ""))
					{
						e.Node.Nodes[0].Remove();
						EnumerateChildren(e.Node);
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show("Unable to expand " + e.Node.FullPath + ":" + ex.ToString());
					//throw;
				}

				if (e.Node.GetNodeCount(false) > 0)
				{
					e.Node.ImageIndex = 1;
					e.Node.SelectedImageIndex = 1;
				}
			}
		}

		private void tvFolders_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
		{
			e.Node.ImageIndex = 0;
			e.Node.SelectedImageIndex = 0;
		}

		private void EnumerateChildren(TreeNode oParent)
		{
			DirectoryInfo oFS = new DirectoryInfo(oParent.FullPath + "\\");

			try
			{
				foreach (DirectoryInfo oDir in oFS.GetDirectories())
				{
					TreeNode oNode = new TreeNode();
					oNode.Text = oDir.Name;
					oNode.ImageIndex = 0;
					oNode.SelectedImageIndex = 0;
					oParent.Nodes.Add(oNode);
					oNode.Nodes.Add("");
				}
			}
			catch (Exception)
			{
				MessageBox.Show("Cannot list folders of " + oParent.FullPath);
			}
		}
	}
}